﻿using M6R小圆柱注液机.Data;
using M6R小圆柱注液机.Pages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FastCtr;
using System.Windows.Forms;
using System.Data;
using FastData;
using System.IO;
using System.Diagnostics;

namespace M6R小圆柱注液机.TaskList
{
    class ProductDataAcq
    {
        private bool processStatus;//进程运行状态
        private bool initWeight_1Success = false;//电子秤1初始化完成
        private bool initWeight_2Success = false;//电子秤2初始化完成
        private bool initWeight_3Success = false;//电子秤3初始化完成
        private bool initWeight_4Success = false;//电子秤4初始化完成
        private bool initScanner_1Success = false;//扫码枪1初始化完成
        private bool initScanner_2Success = false;//扫码枪1初始化完成
        private bool initScanner_3Success = false;//扫码枪1初始化完成
        public int processName;//当前进程名称

        List<object> weight_1ForntData = new List<object>();//电子秤1 前称重数据
        List<object> weight_1BehindData = new List<object>();//电子秤1 后称重数据
        List<object> weight_2ForntData = new List<object>();//电子秤2 前称重数据
        List<object> weight_2BehindData = new List<object>();//电子秤2 后称重数据
        //将list里面的数据进行汇总
        public static List<List<object>> weightForntDataAll = new List<List<object>>();
        public static List<List<object>> weightBehindDataAll = new List<List<object>>();

        private string clipCode;//弹夹的条码
        private string weight_1Code;//1_1电子秤 电子秤扫得条码
        private string weight_2Code;//1_2电子秤 电子秤扫得条码

        static string filePath = new DirectoryInfo("../../../ConfigurationData/TemporaryPara.ini").FullName;
        private long aa = Convert.ToInt64(SaveStatic.ReadIni(filePath, "TemporaryPara", "clipCode"));//弹夹随机码的起始值
        private long bb = Convert.ToInt64(SaveStatic.ReadIni(filePath, "TemporaryPara", "weight1Code"));//1_1电子秤 电子秤随机码的起始值
        private long cc = Convert.ToInt64(SaveStatic.ReadIni(filePath, "TemporaryPara", "weight2Code"));//1_2电子秤 电子称随机码的起始值
        private int serialNumber;//获得序号
        public object lock_num = new object();//上锁
        public int SerialNumber
        {
            get
            {
                lock (lock_num)//加锁可以解决程序的竞争问题，得到的序号，不会有重复的
                {
                    return serialNumber;
                }
            }
            set { lock (lock_num) { serialNumber = value; } }
        }




        /// <summary>
        /// 初始化 
        /// </summary>
        public void Init()
        {
            processStatus = GlobalValues.StatusVariable.status_Program_Running;//获得程序当前的运行状态
            processName = 0;
            serialNumber = GetSerialNumber();//获得序号

            //开启PLC的服务
            if (!PLCServiceInit())
            {
                GlobalValues.log_Helper.DispProcess("PLC服务初始化失败，请检查", "Alarm", true);
                return;
            }
            Task task = new Task(ProgramProcess);
            task.Start();
        }

        /// <summary>
        /// 初始化PLC的服务
        /// </summary>
        private bool PLCServiceInit()
        {
            try
            {
                if (GlobalValues.njOmronPLC.GetServiceStatus() == "Running")
                {
                    GlobalValues.njOmronPLC.StopPLCService(5000);
                    GlobalValues.njOmronPLC.StartPLCService(5000);
                }
                else
                {
                    GlobalValues.njOmronPLC.StartPLCService(5000);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        /// <summary>
        /// 程序运行的流程
        /// 这里采用状态机的方式编写
        /// </summary>
        public void ProgramProcess()
        {
            while (processStatus)
            {
                switch (processName)
                {
                    case 0:
                        Task task1 = new Task(InitWeight_1, TaskCreationOptions.LongRunning);
                        task1.Start();
                        Task task2 = new Task(InitWeight_2, TaskCreationOptions.LongRunning);
                        task2.Start();
                        Task task3 = new Task(InitWeight_3, TaskCreationOptions.LongRunning);
                        task3.Start();
                        Task task4 = new Task(InitWeight_4, TaskCreationOptions.LongRunning);
                        task4.Start();
                        Task.WaitAll(task1, task2, task3, task4);//等待4个电子秤初始化完成，再执行下面的流程

                        if (initWeight_1Success && initWeight_2Success && initWeight_3Success && initWeight_4Success)
                        {
                            processName = 1;
                        }
                        else
                        { return; }
                        break;

                    case 1:
                        InitScanner_1();//执行1号扫码请初始化的行为
                        if (initScanner_1Success)
                        {
                            processName = 2;
                        }
                        else { return; }
                        break;

                    case 2:
                        InitScanner_2();//执行1号扫码请初始化的行为
                        if (initScanner_2Success)
                        {
                            processName = 3;
                        }
                        else { return; }
                        break;

                    case 3:
                        InitScanner_3();//执行1号扫码请初始化的行为
                        if (initScanner_3Success)
                        {
                            processName = 4;
                        }
                        else { return; }
                        break;

                    case 4:
                        GlobalValues.serialPort5.Open();
                        if (GlobalValues.serialPort5.IsOpen)
                        {
                            GlobalValues.log_Helper.DispProcess("MFG信息验证串口通讯初始化完成 . . .", "Info", true);
                        }
                        else
                        {
                            GlobalValues.log_Helper.DispProcess("MFG信息验证串口初始化失败，请检查 . . .", "Alarm", true);
                            GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                            return;
                        }
                        GlobalValues.serialPort6.Open();
                        if (GlobalValues.serialPort6.IsOpen)
                        {
                            GlobalValues.log_Helper.DispProcess("MFG验证电解液串口初始化完成 . . .", "Info", true);
                        }
                        else
                        {
                            GlobalValues.log_Helper.DispProcess("MFG验证电解液串口初始化失败，请检查 . . .", "Alarm", true);
                            GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                            return;
                        }
                        GlobalValues.serialPort7.Open();
                        if (GlobalValues.serialPort7.IsOpen)
                        {
                            GlobalValues.log_Helper.DispProcess("MFG更换电解液串口初始化完成 . . .", "Info", true);
                            processName = 5;
                        }
                        else
                        {
                            GlobalValues.log_Helper.DispProcess("MFG更换电解液串口初始化失败，请检查 . . .", "Alarm", true);
                            GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                            return;
                        }
                        break;

                    case 5:
                        if (GlobalValues.njOmronPLC.Connect())
                        {
                            GlobalValues.log_Helper.DispProcess("PLC通讯初始化完成 . . .", "Info", true);
                            processName = 6;
                        }
                        else
                        {
                            GlobalValues.log_Helper.DispProcess("PLC通讯初始化失败 . . .", "Alarm", true);
                            GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                            return;
                        }
                        break;

                    case 6:
                        if (eventFormToMainForm != null)
                        {
                            eventFormToMainForm(GlobalValues.loginPage);      //显示界面   
                        }

                        if (GlobalValues.StatusVariable.isLoginSuccess)
                        {
                            processName = 7;
                            GlobalValues.log_Helper.DispProcess("操作员登录完成 . . .", "Info", true);
                        }
                        else
                        {
                            GlobalValues.log_Helper.DispProcess("操作员登录失败，请检查 . . .", "Alarm", true);
                            GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                            return;
                        }
                        break;

                    case 7:
                        if (eventFormToMainForm != null)
                        {
                            StartingCheck startCheck = new StartingCheck();//开机MFG信息验证
                            eventFormToMainForm(startCheck);      //显示界面   
                        }
                        GlobalValues.log_Helper.DispProcess("开机MFG信息验证完成 . . .", "Info", true);
                        processName = 8;
                        break;

                    case 8:
                        //初始化时，读取一次PLC中记录的点检状态，如果需要点检，就点检
                        if (true)
                        {
                            if (eventFormToMainForm != null)
                            {
                                eventFormToMainForm(GlobalValues.pointCheck);      //显示界面   
                            }

                            //点检完，把结果反馈给PLC

                            GlobalValues.log_Helper.DispProcess("电子秤点检完成 . . .", "Info", true);
                        }
                        else
                        {
                            GlobalValues.log_Helper.DispProcess("电子秤已点检，无需重复点检 . . .", "Info", true);
                        }
                        GlobalValues.log_Helper.DispProcess("程序允许启动 . . .", "Info", true);
                        processName = 9;

                        GlobalValues.StatusVariable.status_AllowStartProgarm = true;
                        break;

                    case 9:
                        processStatus = false;
                        eventAllowStartProgram(true);//将流程完成的信号传递到主界面，解锁启动程序按钮
                        break;
                    default:
                        break;
                }
                Thread.Sleep(500);
            }
        }

        /// <summary>
        /// 电子秤1 初始化
        /// </summary>
        private void InitWeight_1()
        {
            GlobalValues.serialPort1.Open();//初始化出口
            if (GlobalValues.serialPort1.IsOpen)
            {
                GlobalValues.log_Helper.DispProcess("1_1电子秤正在开机 . . .", "Info", true);
                GlobalValues.Fore_And1.PowerON(8000);//开启电子秤
                if (GlobalValues.serialPort1.SendBackMessageInstant("Q\r\n", 1000) != null)
                {
                    //读取一次电子秤的值，如果可以正常读取上来值，说明电子秤已经初始化完成了
                    initWeight_1Success = true;
                    GlobalValues.log_Helper.DispProcess("1_1电子秤初始化完成 . . .", "Info", true);
                }
                else
                {
                    initWeight_1Success = false;
                    GlobalValues.log_Helper.DispProcess("1_1电子秤初始化失败，请检查 . . .", "Alarm", true);
                    GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                }
            }
            else
            {
                initWeight_1Success = false;
                GlobalValues.log_Helper.DispProcess("1_1电子秤初始化失败，请检查 . . .", "Alarm", true);
                GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
            }
        }
        /// <summary>
        /// 电子秤2 初始化
        /// </summary>
        private void InitWeight_2()
        {
            GlobalValues.serialPort2.Open();//初始化出口
            if (GlobalValues.serialPort2.IsOpen)
            {
                GlobalValues.log_Helper.DispProcess("1_2电子秤正在开机 . . .", "Info", true);
                GlobalValues.Fore_And2.PowerON(8000);//开启电子秤
                if (GlobalValues.serialPort2.SendBackMessageInstant("Q\r\n", 1000) != null)
                {
                    //读取一次电子秤的值，如果可以正常读取上来值，说明电子秤已经初始化完成了
                    initWeight_2Success = true;
                    GlobalValues.log_Helper.DispProcess("1_2电子秤初始化完成 . . .", "Info", true);
                }
                else
                {
                    initWeight_2Success = false;
                    GlobalValues.log_Helper.DispProcess("1_2电子秤初始化失败，请检查 . . .", "Alarm", true);
                    GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                }
            }
            else
            {
                GlobalValues.log_Helper.DispProcess("1_2电子秤初始化失败，请检查 . . .", "Alarm", true);
                GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
            }
        }
        /// <summary>
        /// 电子秤3 初始化
        /// </summary>
        private void InitWeight_3()
        {
            GlobalValues.serialPort3.Open();//初始化出口
            if (GlobalValues.serialPort3.IsOpen)
            {
                GlobalValues.log_Helper.DispProcess("2_1电子秤正在开机 . . .", "Info", true);
                GlobalValues.Behind_And1.PowerON(8000);//开启电子秤
                if (GlobalValues.serialPort3.SendBackMessageInstant("Q\r\n", 1000) != null)
                {
                    //读取一次电子秤的值，如果可以正常读取上来值，说明电子秤已经初始化完成了
                    initWeight_3Success = true;
                    GlobalValues.log_Helper.DispProcess("2_1电子秤初始化完成 . . .", "Info", true);
                }
                else
                {
                    initWeight_3Success = false;
                    GlobalValues.log_Helper.DispProcess("2_1号电子秤初始化失败，请检查 . . .", "Alarm", true);
                    GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                }
            }
            else
            {
                GlobalValues.log_Helper.DispProcess("2_1号电子秤初始化失败，请检查 . . .", "Alarm", true);
                GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
            }
        }
        /// <summary>
        /// 电子秤4 初始化
        /// </summary>
        private void InitWeight_4()
        {
            GlobalValues.serialPort4.Open();//初始化出口
            if (GlobalValues.serialPort4.IsOpen)
            {
                GlobalValues.log_Helper.DispProcess("2_2电子秤正在开机 . . .", "Info", true);
                GlobalValues.Behind_And2.PowerON(8000);//开启电子秤
                if (GlobalValues.serialPort4.SendBackMessageInstant("Q\r\n", 1000) != null)
                {
                    //读取一次电子秤的值，如果可以正常读取上来值，说明电子秤已经初始化完成了
                    initWeight_4Success = true;
                    GlobalValues.log_Helper.DispProcess("2_2电子秤初始化完成 . . .", "Info", true);
                }
                else
                {
                    initWeight_4Success = false;
                    GlobalValues.log_Helper.DispProcess("2_2电子秤初始化失败，请检查 . . .", "Alarm", true);
                    GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                }
            }
            else
            {
                GlobalValues.log_Helper.DispProcess("2_2电子秤初始化失败，请检查 . . .", "Alarm", true);
                GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
            }
        }

        /// <summary>
        /// 1号扫码枪 初始化
        /// </summary>
        private void InitScanner_1()
        {
            GlobalValues.newScanner_1.Connect();
            if (GlobalValues.newScanner_1.ConnectionStatus())
            {
                try
                {
                    initScanner_1Success = true;
                    GlobalValues.newScanner_1.StartReceivingMessage();//开启监听
                    //GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.scanBufferCaler,1000);//清空缓存
                    GlobalValues.log_Helper.DispProcess("1号扫码枪初始化完成 . . .", "Info", true);
                }
                catch (Exception e)
                {
                    initScanner_1Success = false;
                    GlobalValues.log_Helper.DispProcess("1号扫码枪报错： " + e, "Alarm", true);
                    GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                }

            }
            else
            {
                initScanner_1Success = false;
                GlobalValues.log_Helper.DispProcess("1号扫码枪初始化失败 , 请检查 . . .", "Alarm", true);
                GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
            }
        }
        /// <summary>
        /// 2号扫码枪初始化
        /// </summary>
        private void InitScanner_2()
        {
            GlobalValues.newScanner_2.Connect();
            if (GlobalValues.newScanner_2.ConnectionStatus())
            {
                try
                {
                    initScanner_2Success = true;
                    GlobalValues.newScanner_2.StartReceivingMessage();//开启监听
                    //GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.scanBufferCaler, 1000);//清空缓存
                    GlobalValues.log_Helper.DispProcess("2号扫码枪初始化完成 . . .", "Info", true);
                }
                catch (Exception e)
                {
                    initScanner_2Success = false;
                    GlobalValues.log_Helper.DispProcess("2号扫码枪报错： " + e, "Alarm", true);
                    GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                }
            }
            else
            {
                initScanner_2Success = false;
                GlobalValues.log_Helper.DispProcess("2号扫码枪初始化失败 , 请检查 . . .", "Alarm", true);
                GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
            }
        }

        /// <summary>
        /// 3号扫码枪初始化
        /// </summary>
        private void InitScanner_3()
        {
            GlobalValues.newScanner_3.Connect();
            if (GlobalValues.newScanner_3.ConnectionStatus())
            {
                try
                {
                    initScanner_3Success = true;
                    GlobalValues.newScanner_3.StartReceivingMessage();//开启监听
                    //GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.scanBufferCaler, 1000);//清空缓存
                    GlobalValues.log_Helper.DispProcess("3号扫码枪初始化完成 . . .", "Info", true);
                }
                catch (Exception e)
                {
                    initScanner_3Success = false;
                    GlobalValues.log_Helper.DispProcess("3号扫码枪报错： " + e, "Alarm", true);
                    GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
                }

            }
            else
            {
                initScanner_3Success = false;
                GlobalValues.log_Helper.DispProcess("3号扫码枪初始化失败 , 请检查 . . .", "Alarm", true);
                GlobalValues.log_Helper.DispProcess("当前程序不允许启动 . . .", "Alarm", true);
            }
        }


        /// <summary>
        /// 前面板点击了运行程序，这里执行对应行为 - - 开启线程
        /// </summary>
        public void StartProductDataAutoTask()
        {
            try
            {
                GlobalValues.njOmronPLC.StartReceivingMessage(AutoRunningDoWork);
                GlobalValues.log_Helper.DispProcess("主线程已启动", "Info", true);
            }
            catch (Exception e)
            {
                GlobalValues.log_Helper.DispProcess("主线程启动失败，原因：" + e, "Info", true);
            }
        }




        /// <summary>
        /// 自动运行线程
        /// </summary>
        /// <param name="name">触发变量的名称</param>
        /// <param name="value">触发变量的当前值</param>
        private void AutoRunningDoWork(string name, object value2)
        {
            int value = Convert.ToInt32(value2);
            switch (name)
            {
                case GlobalValues.PLCVariableName.weight_1TriggerVariableName:
                    switch (value)
                    {
                        case 0:
                            GlobalValues.log_Helper.DispProcess("1_1电子秤 接收值 : 0", "Info", true);
                            break;
                        case 1:
                            GlobalValues.log_Helper.DispProcess("1_1电子秤 接收值 : 1", "Info", true);
                            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_1TriggerVariableName, 2);
                            sp1.Restart();
                            Weight_1ForntDoWork();
                            sp1.Stop();
                            GlobalValues.log_Helper.DispProcess("称 1耗时：" + sp1.Elapsed.TotalMilliseconds.ToString(), "Alarm", true);
                            break;
                        case 2:
                            GlobalValues.log_Helper.DispProcess("1_1电子秤 接收值 : 2", "Info", true);
                            break;
                        case 4:
                            try
                            {
                                GlobalValues.log_Helper.DispProcess("1_1电子秤 接收值 : 4", "Info", true);
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_1TriggerVariableName, 5);//正在清零
                                GlobalValues.Fore_And1.ZeroV();//清零
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_1TriggerVariableName, 6);//反馈PLC，清零完成
                                GlobalValues.log_Helper.DispProcess("1_1电子秤 清零完成", "Info", true);
                            }
                            catch (Exception)
                            {
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_1TriggerVariableName, -2);//反馈PLC，清零完成
                                GlobalValues.log_Helper.DispProcess("1_1电子秤 清零失败", "Info", true);
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case GlobalValues.PLCVariableName.weight_2TriggerVariableName:
                    switch (value)
                    {
                        case 0:
                            GlobalValues.log_Helper.DispProcess("1_2电子秤 接收值 : 0", "Info", true);
                            break;
                        case 1:
                            GlobalValues.log_Helper.DispProcess("1_2电子秤 接收值 : 1", "Info", true);
                            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_2TriggerVariableName, 2);
                            sp2.Restart();
                            Weight_2ForntDoWork();
                            sp2.Stop();
                            GlobalValues.log_Helper.DispProcess("称 2耗时：" + sp2.Elapsed.TotalMilliseconds.ToString(), "Alarm", true);
                            break;
                        case 2:
                            GlobalValues.log_Helper.DispProcess("1_2电子秤 接收值 : 2", "Info", true);
                            break;
                        case 4:
                            try
                            {
                                GlobalValues.log_Helper.DispProcess("1_2电子秤 接收值 : 4", "Info", true);
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_2TriggerVariableName, 5);//正在清零
                                GlobalValues.Fore_And2.ZeroV();//清零
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_2TriggerVariableName, 6);//反馈PLC，清零完成
                                GlobalValues.log_Helper.DispProcess("1_2电子秤 清零完成", "Info", true);
                            }
                            catch (Exception)
                            {
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_1TriggerVariableName, -2);//反馈PLC，清零完成
                                GlobalValues.log_Helper.DispProcess("1_2电子秤 清零失败", "Info", true);
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case GlobalValues.PLCVariableName.weight_3TriggerVariableName:
                    switch (value)
                    {
                        case 0:
                            GlobalValues.log_Helper.DispProcess("2_1电子秤 接收值 : 0", "Info", true);
                            break;
                        case 1:
                            GlobalValues.log_Helper.DispProcess("2_1电子秤 接收值 : 1", "Info", true);
                            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_3TriggerVariableName, 2);
                            sp3.Restart();
                            Weight_1BehindDoWork();
                            sp3.Stop();
                            GlobalValues.log_Helper.DispProcess("称 3耗时：" + sp3.Elapsed.TotalMilliseconds.ToString(), "Alarm", true);
                            break;
                        case 2:
                            GlobalValues.log_Helper.DispProcess("2_1电子秤 接收值 : 2", "Info", true);
                            break;
                        case 4:
                            try
                            {
                                GlobalValues.log_Helper.DispProcess("2_1电子秤 接收值 : 4", "Info", true);
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_3TriggerVariableName, 5);//正在清零
                                GlobalValues.Behind_And1.ZeroV();//清零
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_3TriggerVariableName, 6);//反馈PLC，清零完成
                                GlobalValues.log_Helper.DispProcess("2_1电子秤 清零完成", "Info", true);
                            }
                            catch (Exception)
                            {
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_3TriggerVariableName, -2);//反馈PLC，清零完成
                                GlobalValues.log_Helper.DispProcess("2_1电子秤 清零失败", "Info", true);
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case GlobalValues.PLCVariableName.weight_4TriggerVariableName:
                    switch (value)
                    {
                        case 0:
                            GlobalValues.log_Helper.DispProcess("2_2电子秤 接收值 : 0", "Info", true);
                            break;
                        case 1:
                            GlobalValues.log_Helper.DispProcess("2_2电子秤 接收值 : 1", "Info", true);
                            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_4TriggerVariableName, 2);
                            sp4.Restart();
                            Weight_2BehindDoWork();
                            sp4.Stop();
                            GlobalValues.log_Helper.DispProcess("称 4耗时：" + sp4.Elapsed.TotalMilliseconds.ToString(), "Alarm", true);
                            break;
                        case 2:
                            GlobalValues.log_Helper.DispProcess("2_2电子秤 接收值 : 2", "Info", true);
                            break;
                        case 4:
                            try
                            {
                                GlobalValues.log_Helper.DispProcess("2_2电子秤 接收值 : 4", "Info", true);
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_4TriggerVariableName, 5);//正在清零
                                GlobalValues.Behind_And2.ZeroV();//清零
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_4TriggerVariableName, 6);//反馈PLC，清零完成
                                GlobalValues.log_Helper.DispProcess("2_2电子秤 清零完成", "Info", true);
                            }
                            catch (Exception)
                            {
                                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_4TriggerVariableName, -2);//反馈PLC，清零完成
                                GlobalValues.log_Helper.DispProcess("2_2电子秤 清零失败", "Info", true);
                            }
                            break;
                        default:
                            break;
                    }
                    break;

                case GlobalValues.PLCVariableName.scanner_1TriggerVariableName:
                    switch (value)
                    {
                        case 0:
                            GlobalValues.log_Helper.DispProcess("1号扫码枪接收PLC的值 : 0", "Info", true);
                            break;
                        case 1:
                            GlobalValues.log_Helper.DispProcess("1号扫码枪接收PLC的值 : 1", "Info", true);
                            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_1TriggerVariableName, 2);//反馈接收状态
                            Scanner_1DoWork();
                            break;
                        case 2:
                            GlobalValues.log_Helper.DispProcess("1号扫码枪接收PLC的值 : 2", "Info", true);
                            break;
                        default:
                            break;
                    }
                    break;

                case GlobalValues.PLCVariableName.scanner_2TriggerVariableName:
                    switch (value)
                    {
                        case 0:
                            GlobalValues.log_Helper.DispProcess("2号扫码枪接收PLC的值 : 0", "Info", true);
                            break;
                        case 1:
                            GlobalValues.log_Helper.DispProcess("2号扫码枪接收PLC的值 : 1", "Info", true);
                            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_2TriggerVariableName, 2);//反馈接收状态
                            Scanner_2DoWork();
                            break;
                        case 2:
                            GlobalValues.log_Helper.DispProcess("2号扫码枪接收PLC的值 : 2", "Info", true);
                            break;
                        default:
                            break;
                    }
                    break;

                case GlobalValues.PLCVariableName.scanner_3TriggerVariableName:
                    switch (value)
                    {
                        case 0:
                            GlobalValues.log_Helper.DispProcess("3号扫码枪接收PLC的值 : 0", "Info", true);
                            break;
                        case 1:
                            GlobalValues.log_Helper.DispProcess("3号扫码枪接收PLC的值 : 1", "Info", true);
                            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_3TriggerVariableName, 2);//反馈接收状态
                            Scanner_3DoWork();
                            break;
                        case 2:
                            GlobalValues.log_Helper.DispProcess("3号扫码枪接收PLC的值 : 2", "Info", true);
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    GlobalValues.log_Helper.DispProcess("接收到PLC发送的未知值，变量名 : " + name + ",值 :  " + value, "Info", true);
                    break;
            }
        }



        //string[] weight_ForntName = { "序号", "时间", "生产型号", "条码", "前称", "NO1" };
        //string[] weight_BehindName = { "时间", "条码", "后称", "NO2", "注液量", "OK/NG", "注液针头", "封装压力", "封装温度", "电解液批次号", "弹夹条码" };

        string[] allName = { "序号", "时间", "条码", "前称", "NO1", "后称", "NO2", "注液量", "OK/NG", "注液针头", "封装压力", "封装温度", "封装时间", "员工工号", "设备编号", "生产型号", "电解液批次号", "弹夹条码" };
        string[] behindName = { "后称", "NO2", "注液量", "OK/NG", "注液针头", "封装压力", "封装温度", "封装时间", "员工工号", "设备编号", "生产型号", "电解液批次号", "弹夹条码" };

        Stopwatch sp1 = new Stopwatch();
        Stopwatch sp2 = new Stopwatch();
        Stopwatch sp3 = new Stopwatch();
        Stopwatch sp4 = new Stopwatch();


        string[] e_Code = new string[10000];
        int xx = 0;
        /// <summary>
        /// 电子秤1 前称重触发时，要执行的工作
        /// </summary>
        private void Weight_1ForntDoWork()
        {

            string code;//二维码
            weight_1ForntData.Add(serialNumber);//序号
            SerialNumber++;
            weight_1ForntData.Add(DateTime.Now);//时间


            if (GlobalValues.StatusVariable.isUseRadomCode)
            {
                xx++;
                code = e_Code[xx] = bb.ToString(); bb++;
                SaveStatic.SaveIni(filePath, "TemporaryPara", "weight1Code", bb.ToString()); //当前随机码保存到ini文件中，避免随机码的重复     
            }
            else
            {


                code = GlobalValues.njOmronPLC.ReadVariable<string>(GlobalValues.PLCVariableName.weight_1Code);

                if (code == "")
                {
                    ////读取上来的条码值为空，触发PLC报警
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_1TriggerVariableName, -1);//反馈称重失败
                    weight_1ForntData.Clear();//清除数据
                    GlobalValues.log_Helper.DispProcess("读取PLC中存储的 1_1电子秤 条码值为空，请检查", "Alarm", true);
                    //当触发此处的报警，后面的程序就不执行了
                    return;
                }
            }
            weight_1ForntData.Add(code);//条码

            string reciverData = GlobalValues.Fore_And1.GetWeightStable(2000);
            if (reciverData == null)
            {
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_1TriggerVariableName, -1);//反馈称重失败
                weight_1ForntData.Clear();//清除数据
                GlobalValues.log_Helper.DispProcess("1_1电子秤称重 失败", "Alarm", true);
                return;
            }

            double forntWeightValue = Math.Round(Convert.ToDouble(reciverData), 3);
            //double forntWeightValue = 0.8;//保留3位小数  0.001
            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_1Value, forntWeightValue);//称重值写给PLC
            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_1TriggerVariableName, 3);//反馈称重完成
            weight_1ForntData.Add(forntWeightValue);//前称读数
            weight_1ForntData.Add("1_1");//表示前称重的哪个电子秤

            SaveStatic.SaveTxt2(GlobalValues.PathVariable.weightFront1_1, weight_1ForntData.ToArray(), true);//保存数据到txt

            for (int i = 0; i < 13; i++)
            {
                weight_1ForntData.Add("");
            }

            //数据写入数据库 
            if (GlobalValues.mysql_Helper.InsertGluingSystemData("tbresult_data", allName, weight_1ForntData, GlobalValues.PathVariable.dataBasePath))
            {
                GlobalValues.log_Helper.DispProcess("1_1电子秤 数据写入数据库成功!  " + "条码：" + code + "; 称重值：" + forntWeightValue, "Info", true);
            }
            else
            {
                //写入失败，重写一次
                if (GlobalValues.mysql_Helper.InsertGluingSystemData("tbresult_data", allName, weight_1ForntData, GlobalValues.PathVariable.dataBasePath))
                {
                    GlobalValues.log_Helper.DispProcess("1_1电子秤 数据重写入数据库成功!  " + "条码：" + code + "; 称重值：" + forntWeightValue, "Info", true);
                }
                else
                {
                    ////数据库写入失败，触发PLC报警
                    //GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.AlarmTriggerVariableName, -1);
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_1TriggerVariableName, -1);//反馈称重失败，让PLC报警
                    weight_1ForntData.Clear();//清除数据
                    GlobalValues.log_Helper.DispProcess("1_1电子秤 数据重写入数据库失败！！", "Alarm", true);
                    return;
                }
            }

            SaveGRRData(GlobalValues.PathVariable.weight1_1, forntWeightValue.ToString(), GlobalValues.StatusVariable.isStartGRR);


            List<object> data = new List<object>(weight_1ForntData);
            weightForntDataAll.Add(data);
            weight_1ForntData.Clear();//清除数据
        }

        int yy = 1;

        /// <summary>
        /// 电子秤1 后称重触发时，要执行的工作
        /// </summary>
        private void Weight_1BehindDoWork()
        {
            string code;
            double forntWeightValue;
            string sql_forntWeight = "";
            DataSet ds = new DataSet();
            if (GlobalValues.StatusVariable.isUseRadomCode)
            {
                code = e_Code[yy];
                yy++;
                sql_forntWeight = "SELECT * FROM `tbresult_data` WHERE `条码`=" + code + "";
                ds = GlobalValues.mysql_Helper.GetDataSet(sql_forntWeight, GlobalValues.PathVariable.dataBasePath);
            }
            else
            {
                code = GlobalValues.njOmronPLC.ReadVariable<string>(GlobalValues.PLCVariableName.weight_3Code);   //后称重的条码，要从PLC获取
                sql_forntWeight = "SELECT * FROM `tbresult_data` WHERE `条码`=" + code + "";
                ds = GlobalValues.mysql_Helper.GetDataSet(sql_forntWeight, GlobalValues.PathVariable.dataBasePath);
                if (code == "")
                {
                    //读取上来的条码值为空，触发PLC报警
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_3TriggerVariableName, -1);//反馈称重失败
                    GlobalValues.log_Helper.DispProcess("读取PLC中存储的 2_1电子秤 条码值为空，请检查", "Alarm", true);
                    //当触发此处的报警，后面的程序就不执行了
                    return;
                }
            }
            if (ds == null)
            {
                ////数据库写入失败，触发PLC报警
                //GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.AlarmTriggerVariableName, -1);
                //读取上来的条码值为空，触发PLC报警
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_3TriggerVariableName, -1);//反馈称重失败
                GlobalValues.log_Helper.DispProcess("2_1电子秤 读取出的条码在数据库中未检索到，请检查", "Alarm", true);
                //当触发此处的报警，后面的程序就不执行了
                return;
            }
            else
            {
                forntWeightValue = Convert.ToDouble(ds.Tables[0].Rows[0][3]);//获取前称的称重值
            }



            string reciverData = GlobalValues.Behind_And1.GetWeightStable(2000);
            if (reciverData == null)
            {
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_3TriggerVariableName, -1);//反馈称重失败
                GlobalValues.log_Helper.DispProcess("2_1电子秤称重 失败", "Alarm", true);
                return;
            }
            double behindWeightValue = Math.Round(Convert.ToDouble(reciverData), 3);
            weight_1BehindData.Add(behindWeightValue);//后称读数
            weight_1BehindData.Add("2_1");////表示后称重的哪个电子秤
            double resultValue = behindWeightValue - forntWeightValue;

            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_3Value, behindWeightValue);//称重值写给PLC
            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.resultValue1, resultValue);//注液量写给PLC
            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_3TriggerVariableName, 3);//反馈称重完成
            weight_1BehindData.Add(resultValue);//注液量
            bool resultIsOK = (resultValue > GlobalValues.CommonVariable.NoteLiquidWeightMin && resultValue < GlobalValues.CommonVariable.NoteLiquidWeightMax) ? true : false;//判断注液结果是否合格
            if (resultIsOK) { weight_1BehindData.Add("OK"); }//OK/NG   
            else { weight_1BehindData.Add("NG"); }

            string needle = "1_1";//注液针头
            weight_1BehindData.Add(needle);
            string pressure = "1000";//封装压力
            weight_1BehindData.Add(pressure);
            string temperature = "100";//封装温度
            weight_1BehindData.Add(temperature);
            string time = "2020-03-03";//封装时间
            weight_1BehindData.Add(time);

            weight_1BehindData.Add(GlobalValues.CommonVariable.operatorNameInfo);//员工工号
            weight_1BehindData.Add(GlobalValues.CommonVariable.mechineInfo);//设备编号
            weight_1BehindData.Add(GlobalValues.CommonVariable.finishedProductCodingInfo);//生产型号
            weight_1BehindData.Add(GlobalValues.CommonVariable.electrolyteNumberInfo);//电解液批次号
            string cartridgeCode = "1000000000";//弹夹条码
            weight_1BehindData.Add(cartridgeCode);

            SaveNoteLiquidValue(needle, resultValue);//保存注液量的值到TXT文本中


            string[] xx = new string[13];
            for (int i = 0; i < weight_1BehindData.Count; i++) { xx[i] = weight_1BehindData[i].ToString(); }



            //数据写入数据库 
            if (GlobalValues.mysql_Helper.Update("tbresult_data", behindName, xx, "条码", code, GlobalValues.PathVariable.dataBasePath))
            {
                GlobalValues.log_Helper.DispProcess("2_1电子秤 数据写入数据库成功!  " + "条码：" + code + "; 称重值：" + behindWeightValue + " ; 注液量：" + resultValue, "Info", true);
            }
            else
            {
                //写入失败，重写一次
                if (GlobalValues.mysql_Helper.Update("tbresult_data", behindName, xx, "条码", code, GlobalValues.PathVariable.dataBasePath))
                {
                    GlobalValues.log_Helper.DispProcess("2_1电子秤 数据重写入数据库成功!  " + "条码：" + code + "; 称重值：" + behindWeightValue + " ; 注液量：" + resultValue, "Info", true);
                }
                else
                {
                    ////数据库写入失败，触发PLC报警
                    //GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.AlarmTriggerVariableName, -1);
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_3TriggerVariableName, -1);//反馈称重失败
                    weight_1BehindData.Clear();//清除数据
                    GlobalValues.log_Helper.DispProcess("2_1电子秤 数据重写入数据库失败！！", "Alarm", true);
                    return;
                }
            }


            SaveGRRData(GlobalValues.PathVariable.weight2_1, behindWeightValue.ToString(), GlobalValues.StatusVariable.isStartGRR);


            weight_1BehindData.Insert(0, code);//插入条码
            SaveStatic.SaveTxt2(GlobalValues.PathVariable.all_1, weight_1BehindData.ToArray(), true);//保存数据到txt
            List<object> data = new List<object>(weight_1BehindData);
            weightBehindDataAll.Add(data);
            weight_1BehindData.Clear();//清除数据


            if (resultIsOK)
            {
                //GlobalValues.njOmronPLC.WriteVariable(PLC扫描.前电子秤1数据内存名称[1], "OK");//写入plc数据内存ok
                SaveStatic.SaveTxtT("E:\\MatchData\\" + code + ".dbf", "序号\tPC用户名\t时间\t生产型号\t电解液批号\t条码1\t前称1读数\t后称1读数\t注液量1\tOK/NG1\t注液针头\t封装压力\t封装温度\t弹夹条码1\t员工工号\t设备编号\t条码2\t前称2读数\t后称2读数\t注液量2\tOK/NG2\t注液针头\t封装压力\t封装温度\t弹夹条码2\t员工工号\t预留2\r\n" +
                                                    "0" + "\t" + GlobalValues.CommonVariable.mechineInfo + "\t" + ds.Tables[0].Rows[0][1] + "\t" + GlobalValues.CommonVariable.finishedProductCodingInfo + "\t" +
                                                   GlobalValues.CommonVariable.electrolyteNumberInfo + "\t" + code + "\t" + ds.Tables[0].Rows[0][3] + "\t" + behindWeightValue + "\t" +
                                                  resultValue + "\t" + "OK" + "\t" + needle + "\t" + pressure + "\t" +
                                                   temperature + "\t" + cartridgeCode + "\t" + GlobalValues.CommonVariable.operatorNameInfo + "\t" + GlobalValues.CommonVariable.mechineInfo + "\t" +
                                                   code + "\t" + ds.Tables[0].Rows[0][1] + "\t" + behindWeightValue + "\t" + resultValue + "\t" + "OK" + "\t" + needle + "\t" + pressure + "\t" + temperature + "\t" + cartridgeCode + "\t" + GlobalValues.CommonVariable.operatorNameInfo + "\t" + "---" + "\r\n" + "1", false);
            }
        }


        string[] e_Code2 = new string[10000];
        int xx2 = 0;

        /// <summary>
        /// 电子秤2 前称重触发时，要执行的工作
        /// </summary>
        private void Weight_2ForntDoWork()
        {
            string code;//二维码
            weight_2ForntData.Add(serialNumber);//序号
            SerialNumber++;
            weight_2ForntData.Add(DateTime.Now);//时间
            //weight_2ForntData.Add(GlobalValues.CommonVariable.finishedProductCodingInfo);//生产型号


            if (GlobalValues.StatusVariable.isUseRadomCode)
            {
                xx2++;
                //这后面要删掉的
                code = e_Code2[xx2] = cc.ToString(); cc++;
                SaveStatic.SaveIni(filePath, "TemporaryPara", "weight2Code", cc.ToString());//当前随机码保存到ini文件中，避免随机码的重复     
            }
            else
            {
                code = GlobalValues.njOmronPLC.ReadVariable<string>(GlobalValues.PLCVariableName.weight_2Code);
                if (code == "")
                {
                    ////读取上来的条码值为空，触发PLC报警
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_2TriggerVariableName, -1);//反馈称重失败
                    weight_2ForntData.Clear();//清除数据
                    GlobalValues.log_Helper.DispProcess("读取PLC中存储的 1_2电子秤 条码值为空，请检查", "Alarm", true);
                    //当触发此处的报警，后面的程序就不执行了
                    return;
                }
            }
            weight_2ForntData.Add(code);//条码

            string reciverData = GlobalValues.Fore_And2.GetWeightStable(2000);
            if (reciverData == null)
            {
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_2TriggerVariableName, -1);//反馈称重失败
                weight_2ForntData.Clear();//清除数据
                GlobalValues.log_Helper.DispProcess("1_2电子秤称重 失败", "Alarm", true);
                return;
            }
            double forntWeightValue = Math.Round(Convert.ToDouble(reciverData), 3);
            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_2Value, forntWeightValue);//称重值写给PLC
            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_2TriggerVariableName, 3);//反馈称重完成
            weight_2ForntData.Add(forntWeightValue);//前称读数
            weight_2ForntData.Add("1_2");//表示前称重的哪个电子秤

            SaveStatic.SaveTxt2(GlobalValues.PathVariable.weightFront1_2, weight_2ForntData.ToArray(), true);//保存数据到txt

            for (int i = 0; i < 13; i++)
            {
                weight_2ForntData.Add("");
            }

            //数据写入数据库 
            if (GlobalValues.mysql_Helper.InsertGluingSystemData("tbresult_data", allName, weight_2ForntData, GlobalValues.PathVariable.dataBasePath))
            {
                GlobalValues.log_Helper.DispProcess("1_2电子秤 数据写入数据库成功!  " + "条码：" + code + "; 称重值：" + forntWeightValue, "Info", true);
            }
            else
            {
                //写入失败，重写一次
                if (GlobalValues.mysql_Helper.InsertGluingSystemData("tbresult_data", allName, weight_2ForntData, GlobalValues.PathVariable.dataBasePath))
                {
                    GlobalValues.log_Helper.DispProcess("1_2电子秤 数据重写入数据库成功!  " + "条码：" + code + "; 称重值：" + forntWeightValue, "Info", true);
                }
                else
                {
                    ////数据库写入失败，触发PLC报警
                    //GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.AlarmTriggerVariableName, -1);
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_2TriggerVariableName, -1);//反馈称重失败
                    weight_2ForntData.Clear();//清除数据
                    GlobalValues.log_Helper.DispProcess("1_2电子秤 数据重写入数据库失败！！", "Alarm", true);
                    return;
                }
            }

            SaveGRRData(GlobalValues.PathVariable.weight1_2, forntWeightValue.ToString(), GlobalValues.StatusVariable.isStartGRR);

            List<object> data = new List<object>(weight_2ForntData);
            weightForntDataAll.Add(data);
            weight_2ForntData.Clear();//清除数据
        }

        int yy2 = 1;



        /// <summary>
        /// 电子秤2 后称重触发时，要执行的工作
        /// </summary>
        private void Weight_2BehindDoWork()
        {
            string code;
            double forntWeightValue;
            string sql_forntWeight = "";
            DataSet ds = new DataSet();

            if (GlobalValues.StatusVariable.isUseRadomCode)
            {
                code = e_Code2[yy2];
                sql_forntWeight = "SELECT * FROM `tbresult_data` WHERE `条码`=" + code + "";
                ds = GlobalValues.mysql_Helper.GetDataSet(sql_forntWeight, GlobalValues.PathVariable.dataBasePath);
                yy2++;
            }
            else
            {
                code = GlobalValues.njOmronPLC.ReadVariable<string>(GlobalValues.PLCVariableName.weight_4Code);   //后称重的条码，要从PLC获取
                sql_forntWeight = "SELECT * FROM `tbresult_data` WHERE `条码`=" + code + "";
                ds = GlobalValues.mysql_Helper.GetDataSet(sql_forntWeight, GlobalValues.PathVariable.dataBasePath);
                if (code == "")
                {
                    ////读取上来的条码值为空，触发PLC报警
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_4TriggerVariableName, -1);//反馈称重失败
                    GlobalValues.log_Helper.DispProcess("读取PLC中存储的 2_2电子秤 条码值为空，请检查", "Alarm", true);
                    //当触发此处的报警，后面的程序就不执行了
                    return;
                }
            }
            if (ds == null)
            {
                ////数据库写入失败，触发PLC报警
                //GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.AlarmTriggerVariableName, -1);
                //读取上来的条码值为空，触发PLC报警
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_4TriggerVariableName, -1);//反馈称重失败
                GlobalValues.log_Helper.DispProcess("2_2电子秤 读取出的条码在数据库中未检索到，请检查", "Alarm", true);
                //当触发此处的报警，后面的程序就不执行了
                return;
            }
            else
            {
                forntWeightValue = Convert.ToDouble(ds.Tables[0].Rows[0][3]);//获取前称的称重值
            }

            string reciverData = GlobalValues.Behind_And2.GetWeightStable(2000);
            if (reciverData == null)
            {
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_4TriggerVariableName, -1);//反馈称重失败
                GlobalValues.log_Helper.DispProcess("2_2电子秤称重 失败", "Alarm", true);
                return;
            }
            double behindWeightValue = Math.Round(Convert.ToDouble(reciverData), 3);

            weight_2BehindData.Add(behindWeightValue);//后称读数
            weight_2BehindData.Add("2_2");////表示后称重的哪个电子秤
            double resultValue = behindWeightValue - forntWeightValue;

            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_4Value, behindWeightValue);//称重值写给PLC
            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.resultValue2, resultValue);//注液量写给PLC
            GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_4TriggerVariableName, 3);//反馈称重完成
            weight_2BehindData.Add(resultValue);//注液量
            bool resultIsOK = (resultValue > GlobalValues.CommonVariable.NoteLiquidWeightMin && resultValue < GlobalValues.CommonVariable.NoteLiquidWeightMax) ? true : false;//判断注液结果是否合格
            if (resultIsOK) { weight_2BehindData.Add("OK"); }//OK/NG   
            else { weight_2BehindData.Add("NG"); }

            string needle = "1_1";//注液针头
            weight_2BehindData.Add(needle);
            string pressure = "1000";//封装压力
            weight_2BehindData.Add(pressure);
            string temperature = "100";//封装温度
            weight_2BehindData.Add(temperature);
            string time = "2020-03-30";//封装时间
            weight_2BehindData.Add(time);


            weight_2BehindData.Add(GlobalValues.CommonVariable.operatorNameInfo);//员工工号
            weight_2BehindData.Add(GlobalValues.CommonVariable.mechineInfo);//设备编号
            weight_2BehindData.Add(GlobalValues.CommonVariable.finishedProductCodingInfo);//生产型号
            weight_2BehindData.Add(GlobalValues.CommonVariable.electrolyteNumberInfo);//电解液批次号
            string cartridgeCode = "1000000000";//弹夹条码
            weight_2BehindData.Add(cartridgeCode);


            SaveNoteLiquidValue(needle, resultValue);//保存注液量的值到TXT文本中

            string[] xx = new string[13];
            for (int i = 0; i < weight_2BehindData.Count; i++) { xx[i] = weight_2BehindData[i].ToString(); }



            //数据写入数据库 
            if (GlobalValues.mysql_Helper.Update("tbresult_data", behindName, xx, "条码", code, GlobalValues.PathVariable.dataBasePath))
            {
                GlobalValues.log_Helper.DispProcess("2_2电子秤 数据写入数据库成功!  " + "条码：" + code + "; 称重值：" + behindWeightValue + " ; 注液量：" + resultValue, "Info", true);
            }
            else
            {
                //写入失败，重写一次
                if (GlobalValues.mysql_Helper.Update("tbresult_data", behindName, xx, "条码", code, GlobalValues.PathVariable.dataBasePath))
                {
                    GlobalValues.log_Helper.DispProcess("2_2电子秤 数据重写入数据库成功!  " + "条码：" + code + "; 称重值：" + behindWeightValue + " ; 注液量：" + resultValue, "Info", true);
                }
                else
                {
                    ////数据库写入失败，触发PLC报警
                    //GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.AlarmTriggerVariableName, -1);
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.weight_4TriggerVariableName, -1);//反馈称重失败
                    weight_2BehindData.Clear();//清除数据
                    GlobalValues.log_Helper.DispProcess("2_2电子秤 数据重写入数据库失败！！", "Alarm", true);
                    return;
                }
            }

            SaveGRRData(GlobalValues.PathVariable.weight2_2, behindWeightValue.ToString(), GlobalValues.StatusVariable.isStartGRR);

            weight_2BehindData.Insert(0, code);//插入条码
            SaveStatic.SaveTxt2(GlobalValues.PathVariable.all_2, weight_2BehindData.ToArray(), true);//保存数据到txt
            List<object> data = new List<object>(weight_2BehindData);
            weightBehindDataAll.Add(data);
            weight_2BehindData.Clear();//清除数据


            if (resultIsOK)
            {
                //GlobalValues.njOmronPLC.WriteVariable(PLC扫描.前电子秤1数据内存名称[1], "OK");//写入plc数据内存ok
                SaveStatic.SaveTxtT("E:\\MatchData\\" + code + ".dbf", "序号\tPC用户名\t时间\t生产型号\t电解液批号\t条码1\t前称1读数\t后称1读数\t注液量1\tOK/NG1\t注液针头\t封装压力\t封装温度\t弹夹条码1\t员工工号\t设备编号\t条码2\t前称2读数\t后称2读数\t注液量2\tOK/NG2\t注液针头\t封装压力\t封装温度\t弹夹条码2\t员工工号\t预留2\r\n" +
                                                    "0" + "\t" + GlobalValues.CommonVariable.mechineInfo + "\t" + ds.Tables[0].Rows[0][1] + "\t" + GlobalValues.CommonVariable.finishedProductCodingInfo + "\t" +
                                                   GlobalValues.CommonVariable.electrolyteNumberInfo + "\t" + code + "\t" + ds.Tables[0].Rows[0][3] + "\t" + behindWeightValue + "\t" +
                                                  resultValue + "\t" + "OK" + "\t" + needle + "\t" + pressure + "\t" +
                                                   temperature + "\t" + cartridgeCode + "\t" + GlobalValues.CommonVariable.operatorNameInfo + "\t" + GlobalValues.CommonVariable.mechineInfo + "\t" +
                                                   code + "\t" + ds.Tables[0].Rows[0][1] + "\t" + behindWeightValue + "\t" + resultValue + "\t" + "OK" + "\t" + needle + "\t" + pressure + "\t" + temperature + "\t" + cartridgeCode + "\t" + GlobalValues.CommonVariable.operatorNameInfo + "\t" + "---" + "\r\n" + "1", false);
            }
        }




        /// <summary>
        /// 从数据库中获得序号
        /// </summary>
        /// <returns></returns>
        private int GetSerialNumber()
        {
            string sql_GetSerialNumber = "SELECT MAX(`序号`)FROM tbresult_data ";//序号，后面可以根据数据的数量来反馈

            DataSet ds = GlobalValues.mysql_Helper.GetDataSet(sql_GetSerialNumber, GlobalValues.PathVariable.dataBasePath);
            if (ds.Tables[0].Rows[0][0].GetType().ToString() != "System.DBNull")
            {
                return (Convert.ToInt32(ds.Tables[0].Rows[0][0]) + 1);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 保存注液量到TXT文本中
        /// 用于chart显示数据
        /// </summary>
        private void SaveNoteLiquidValue(string neddleNumber, double value)
        {
            switch (neddleNumber)
            {
                case "1_1":
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileNeedle_1Value, value.ToString("0.000"), true);//图表
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileCPK_1, value.ToString("0.000"), true);//CPK
                    break;
                case "1_2":
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileNeedle_2Value, value.ToString("0.000"), true);//图表
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileCPK_2, value.ToString("0.000"), true);//CPK
                    break;
                case "2_1":
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileNeedle_3Value, value.ToString("0.000"), true);//图表
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileCPK_3, value.ToString("0.000"), true);//CPK
                    break;
                case "2_2":
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileNeedle_4Value, value.ToString("0.000"), true);//图表
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileCPK_4, value.ToString("0.000"), true);//CPK
                    break;
                case "3_1":
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileNeedle_5Value, value.ToString("0.000"), true);//图表
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileCPK_5, value.ToString("0.000"), true);//CPK
                    break;
                case "3_2":
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileNeedle_6Value, value.ToString("0.000"), true);//图表
                    SaveStatic.SaveTxt(GlobalValues.PathVariable.fileCPK_6, value.ToString("0.000"), true);//CPK
                    break;
                default:
                    break;
            }
        }


        /// <summary>
        /// GRR数据保存
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="value">值</param>
        /// <param name="isSave">是否存储GRR数据</param>
        public void SaveGRRData(string path, string value, bool isSave)
        {
            if (isSave)
            {
                SaveStatic.SaveTxt(path, value, true);//图表
            }
        }

        /// <summary>
        /// 1号扫码枪（弹夹）接收到PLC触发信号后的行为
        /// </summary>
        private void Scanner_1DoWork()
        {
            if (!GlobalValues.StatusVariable.isUseRadomCode)
            {
                string x = GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.StartTrigger, 5000);
                if (x != null)
                {
                    clipCode = x.Substring(0, x.IndexOf("\r"));//扫条码，开始扫描

                    //GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.StopTrigger, 200);//停止扫码
                    //GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.scanBufferCaler, 200);//清空缓存信息

                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_1CodeVariableName, clipCode);//反馈条码
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_1TriggerVariableName, 3);//反馈接收信息
                }
                else
                {
                    GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.StopTrigger, 1000);//扫条码,扫描关闭
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_1TriggerVariableName, -1);//反馈给PLC--报错
                    GlobalValues.log_Helper.DispProcess("1号扫码枪条码读取失败", "Alarm", true);
                    return;
                }
            }
            else
            {
                clipCode = aa.ToString();//使用随机码
                aa++;
                SaveStatic.SaveIni(filePath, "TemporaryPara", "clipCode", aa.ToString());  //当前随机码保存到ini文件中，避免随机码的重复               
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_1CodeVariableName, clipCode);//把条码写给PLC
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_1TriggerVariableName, 3);//反馈接收信息
            }
            GlobalValues.log_Helper.DispProcess("弹夹条码：" + clipCode, "Info", true);
        }


        /// <summary>
        /// 2号扫码枪（1_1电子秤电子秤）
        /// </summary>
        private void Scanner_2DoWork()
        {
            if (!GlobalValues.StatusVariable.isUseRadomCode)
            {
                string x = GlobalValues.newScanner_2.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.StartTrigger, 5000);
                if (x != null)
                {
                    weight_1Code = x.Substring(0, x.IndexOf("\r"));//扫条码

                    //GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.StopTrigger, 200);//停止扫码
                    //GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.scanBufferCaler, 200);//清空缓存信息

                    string sql = "SELECT * FROM `tbforntwight_data` WHERE `条码` LIKE" + weight_1Code + "%";
                    DataSet dt = GlobalValues.mysql_Helper.GetDataSet(sql, GlobalValues.PathVariable.dataBasePath);
                    if (dt == null)
                    {

                    }
                    else
                    {
                        int count = dt.Tables[0].Rows.Count;
                        if (count >= 1)
                        {
                            //说明条码存在重复，先报错给PLC，再修改二维码的值
                            //GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.AlarmTriggerVariableName, -1);
                            weight_1Code += count.ToString();
                        }
                    }

                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_2CodeVariableName, weight_1Code);//反馈条码
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_2TriggerVariableName, 3);//反馈接收信息                  
                }
                else
                {
                    GlobalValues.newScanner_2.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.StopTrigger, 1000);//扫条码,扫描关闭
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_2TriggerVariableName, -1);//反馈给PLC--报错
                    GlobalValues.log_Helper.DispProcess("2号扫码枪条码读取失败", "Alarm", true);
                    return;
                }
            }
            else
            {
                weight_1Code = bb.ToString();
                bb++;
                SaveStatic.SaveIni(filePath, "TemporaryPara", "weight1Code", bb.ToString()); //当前随机码保存到ini文件中，避免随机码的重复     
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_2CodeVariableName, weight_1Code);//把条码写给PLC
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_2TriggerVariableName, 3);//反馈接收信息
            }
            GlobalValues.log_Helper.DispProcess("1_1电子秤条码：" + weight_1Code, "Info", true);
        }


        /// <summary>
        /// 3号扫码枪（1_2电子秤电子秤）
        /// </summary>
        private void Scanner_3DoWork()
        {
            if (!GlobalValues.StatusVariable.isUseRadomCode)
            {
                string x = GlobalValues.newScanner_3.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.StartTrigger, 5000);

                if (x != null)
                {
                    weight_2Code = x.Substring(0, x.IndexOf("\r"));//扫条码
                    //GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.StopTrigger, 200);//停止扫码
                    //GlobalValues.newScanner_1.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.scanBufferCaler, 200);//清空缓存信息
                    string sql = "SELECT * FROM `tbforntwight_data` WHERE `条码` LIKE" + weight_2Code + "%";
                    DataSet dt = GlobalValues.mysql_Helper.GetDataSet(sql, GlobalValues.PathVariable.dataBasePath);

                    if (dt == null)
                    {

                    }
                    else
                    {
                        int count = dt.Tables[0].Rows.Count;
                        if (count >= 1)
                        {
                            //说明条码存在重复，先报错给PLC，再修改二维码的值
                            //GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.AlarmTriggerVariableName, -1);
                            weight_1Code += count.ToString();
                        }
                    }

                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_3CodeVariableName, weight_2Code);//反馈条码
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_3TriggerVariableName, 3);//反馈接收信息
                }
                else
                {
                    GlobalValues.newScanner_3.SendBackMessageInstant(GlobalValues.ScannerTrigherCommand.StopTrigger, 1000);//扫条码,扫描关闭
                    GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_3TriggerVariableName, -1);
                    GlobalValues.log_Helper.DispProcess("3号扫码枪条码读取失败", "Alarm", true);
                    return;
                }
            }
            else
            {
                weight_2Code = cc.ToString();//使用随机码
                cc++;
                SaveStatic.SaveIni(filePath, "TemporaryPara", "weight2Code", cc.ToString());//当前随机码保存到ini文件中，避免随机码的重复     
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_3CodeVariableName, weight_2Code);//把条码写给PLC
                GlobalValues.njOmronPLC.WriteVariable(GlobalValues.PLCVariableName.scanner_3TriggerVariableName, 3);//反馈接收信息
            }
            GlobalValues.log_Helper.DispProcess("1_2电子秤条码：" + weight_2Code, "Info", true);
        }















        public delegate void delegateAllowStartProgram(bool status);
        /// <summary>
        /// //将流程完成的信号传递到主界面，解锁启动程序按钮
        /// </summary>
        public event delegateAllowStartProgram eventAllowStartProgram;
        public delegate void delegateFormToMainForm(Form form);
        public event delegateFormToMainForm eventFormToMainForm;


        public void Test()
        {
            //开启线程，去处理触发后的行为             
            Task t1 = new Task(Weight_1ForntDoWork, TaskCreationOptions.LongRunning);
            t1.Start();
        }

        public void Test2()
        {
            //开启线程，去处理触发后的行为
            Task t2 = new Task(Weight_1BehindDoWork, TaskCreationOptions.LongRunning);
            t2.Start();
        }

        public void Test3()
        {
            //开启线程，去处理触发后的行为
            Task t3 = new Task(Weight_2ForntDoWork, TaskCreationOptions.LongRunning);
            t3.Start();
        }

        public void Test4()
        {
            //开启线程，去处理触发后的行为
            Task t4 = new Task(Weight_2BehindDoWork, TaskCreationOptions.LongRunning);
            t4.Start();
        }



    }
}
